package com.xzc.kafka.action.consumer;

import com.alibaba.fastjson.JSON;
import com.xzc.kafka.action.pojo.User;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.Deserializer;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.util.Arrays;
import java.util.Map;
import java.util.Properties;

public class _2UserDeserializer implements Deserializer {


    @Override
    public void configure(Map configs, boolean isKey) {
        //压根没调用
    }

    // props.put("value.deserializer","com.xzc.kafka.action.consumer._2UserDeserializer");
    @Override
    public Object deserialize(String topic, byte[] data) {
        User user = null;
        try {
//            user = objectMapper.readValue(data, User.class);
            user = JSON.parseObject(data, User.class);
        } finally {
            return user;
        }
    }

    @Override
    public void close() {

    }

    public static void main(String[] args) {
        String topicName = "test-topic1";

        String groupID = "test-group";
        Properties props = new Properties();
        props.put("bootstrap.servers", "es1:19092,es2:19092,es3:19092");
        props.put("group.id", groupID);
        props.put("enable.auto.commit", true);
//        props.put("enable.auto.commit", false);
        props.put("auto.commit.interval.ms", "1000");
        props.put("auto.offset.reset", "earliest");
//        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
//        props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");

        KafkaConsumer<String, User> consumer = new KafkaConsumer<>(props, new StringDeserializer(), new _2UserDeserializer());
        consumer.subscribe(Arrays.asList(topicName));

        try {
            while (true) {
                //等待1000，可以让consumer醒过来，处理点其它事情
                ConsumerRecords<String, User> records = consumer.poll(1000);
                for (ConsumerRecord<String, User> record : records) {
                    System.out.printf("offset=%d key=%s val=%s\n",
                            record.offset(),
                            record.key(),
                            record.value());
                }
            }
        } finally {
            consumer.close();
        }
    }
}
